// import Big from 'big.js'; //处理计算精度问题 times-乘  div-除  minus-减 plus-加 mod-取余 pow-次方
import $store from '@/store/index.js'
const $goodsList = $store?.state?.$goodsList


async function postData(url = '', data = {}, ticket) {
  // Default options are marked with *
  const response = await fetch(url, {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, *cors, same-origin
    // cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    // credentials: 'same-origin', // include, *same-origin, omit
    headers: {
      'Content-Type': 'application/json'
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify(data) // body data type must match "Content-Type" header
  });
  return response.json(); // parses JSON response into native JavaScript objects
}

// postData('https://example.com/answer', {
//     answer: 42
//   })
//   .then(data => {
//     console.log(data); // JSON data parsed by `data.json()` call
//   });

const toFixed2 = (num) => {
  return !isNaN(Number(num)) ? Number(Number(num).toFixed(2)) : 0
}

/**
 * @description 计算账单数据
 * @property {Array}  list - 购物车商品列表
 * @property {String} type = [vip|discount|change|free|coupon] 会员价、整单折扣、整单改价、免单、优惠券
 * @property {Number} discountAmount - 折扣比例/减免金额
 * @property {Number} subtractPrice - 抹零金额
 * @property {Number} vipPayAmount  - 会员支付金额
 * @property {Number} integralPayAmount  - 积分抵扣金额
 * @property {Object} couponInfo  - 优惠券信息
 * @property {Object} vipInfo  - 会员信息
 * @property {Object} vipSetting  - 会员设置 enable_member_discount,satisfy_deduction_integral,member_birth_multiple,integral_deduction,enable_member_integral
 * @property {Array} activityList - 活动列表
 */

export const calcBillResult = (list = [], type = '', discountAmount = 0, subtractPrice = 0, billResult = {},
  vipPayAmount = 0, integralPayAmount = 0, couponInfo = null, vipInfo = null, vipSetting = null, activityList = null
) => {

  const curMember = vipInfo || $store?.state?.$curMember
  const $integralSetting = vipSetting || $store?.state?.$integralSetting
  const enable_member_discount = $integralSetting?.enable_member_discount
  let activites = activityList || $store.state?.$activites //活动列表
  let $activityList = activityList || $store?.state?.$activityList || []
  $activityList = $activityList.reduce((pre, cur) => {
    let activityIndex = pre.findIndex(item => item.promotion_no === cur.promotion_no)
    if (activityIndex !== -1) {
      pre[activityIndex]._goods_nos.push(cur.goods_no)
    } else {
      cur._goods_nos = [cur.goods_no]
      pre.push(cur)
    }
    return pre
  }, [])
  activites = $activityList
  if (!curMember?.id && type === 'vip') {
    type = ''
  }

  const result = {
    order_total_amount: 0, // 订单总金额，不使用优惠的
    order_amount: 0, //订单金额 折扣、优惠、抹零过后的金额
    change_price: 0, //整单改价金额

    // member_no: curMember?.member_no || curMember?.menber_no,
    // order_channel: '台式消费机', //订单来源
    channel_source: "台式消费机", //订单来源
    // sales_clerk: $store?.state?.$loginUser?.user_no, //收银员工号
    // sales_clerk_staff: $store?.state?.$curAssistant?.staff_no, //营业员工号
    discount_mode: '无', //  打折/优惠方式 enum('无','打折','减免')
    discount_type: '不优惠', // enum('不优惠','整单手动打折/改价','免单')

    member_discount: 0, //会员价优惠金额
    discount_reduction_amount: 0, //	折扣/减免金额
    free_discount_amount: 0, //免单优惠金额
    cash_reduction_amount: 0, //抹零金额
    // cash_reduction_amount: billResult?.cash_reduction_amount || 0, //抹零金额

    "discount_full_decrement": 0, // 促销-满额减现 折扣金额
    "discount_direct": 0, //	促销-直接折扣 折扣金额

    "integral_deduction": 0, //积分抵扣金额
    // "integral_deduction": billResult?.integral_deduction || 0, //积分抵扣

    coupon_discount: 0, // 优惠券优惠--金额
    coupon_no: '', // 优惠券编号

    discount_amount: 0, // 总优惠金额

    discount_reason: '', //打折/免单原因编号
    discount_reason_name: "", //打折/免单原因
    order_detail: [], // 订单商品详情
    // ...billResult
    _activites: [], // 参加的所有营销活动
    _order_amount: billResult?._order_amount || 0,

  }


  if (Array.isArray(activites) && activites.length > 0) {
    // if (type !== 'vip' && Array.isArray(activites) && activites.length > 0) {
    activites = activites.filter(item => {
      if (item?.participants === '指定会员等级') {
        if (item?.member_level_name && curMember?.member_level_no && item.member_level_name.indexOf(curMember
            ?.member_level_no) == -1) {
          // 不在指定会员等级里
          return false
        } else if (!curMember?.member_level_no) {
          return false
        }
        // if (item?.member_level_name && curMember?.member_level_no && curMember
        //   ?.member_level_no === item?.member_level_name) {} else {
        //   return false
        // }
      }
      if (item?.weekly_take_effect) {
        let weekly = new Date().getDay() // 0-6
        let weekMap = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
        if (item.weekly_take_effect.indexOf(weekMap[weekly]) !== -1) {
          return true
        }
      }
    })

    if (Array.isArray(list) && list.length > 0) {
      list = list.map(item => {
        item._activites = activites.filter(e => e._goods_nos.includes(item.goods_no))
        let onlyActivite = item._activites.find(e => (e.promotion_mode === '满额减现' && e
          .whether_multiplication === '是') || e.promotion_mode === '直接折扣')
        if (onlyActivite) {
          // 都是不倍增且满额减现的才可以叠加 有倍增的就只用倍增的 有直接折扣的就只用直接折扣的 
          item._activites = [onlyActivite]
        }
        return item
      })
    }

    activites = activites.filter(activite => {
      if (list.find(item => item._activites && item._activites.find(e => e.promotion_no && e.promotion_no ===
          activite.promotion_no))) {
        return true
      }
    })

    if (Array.isArray(activites) && activites.length > 0) {
      activites.forEach(activite => {
        const curGoods = list.filter(item => item._activites.find(e => e.promotion_no && e.promotion_no ===
          activite.promotion_no))
        if (Array.isArray(curGoods) && curGoods.length > 0) {
          // activite._curGoods = curGoods
          // 符合此活动的商品总价
          let price = curGoods.reduce((pre, cur) => {
            pre += cur.sale_price * cur.amount
            return pre
          }, 0)
          activite._discountGoodsList = list.filter(item => item._activites && item._activites.find(e => e
            .promotion_no && e.promotion_no === activite.promotion_no)).map(item => item.goods_no)
          if (activite.promotion_mode === '满额减现') {
            if (price >= activite?.buy_full && activite?.discount_amount) {
              let rate = parseInt(price / activite?.buy_full)
              let discount_full_decrement = 0
              if (rate > 0) {

                if (activite.whether_multiplication === '否') {
                  // 不倍增
                  rate = 1
                }
                discount_full_decrement = -toFixed2(activite?.discount_amount * rate)
                activite._discount_full_decrement = discount_full_decrement

                activite._rate = rate
                result.discount_full_decrement += discount_full_decrement
                result.discount_amount += discount_full_decrement // 满额减现
                result._activites.push(activite)
              }
            }
          } else if (activite.promotion_mode === '直接折扣') {
            let discount = activite.direct_discount || activite.discount || 100
            let discount_direct = -toFixed2(price * (100 - discount) / 100) //直接折扣减免的金额
            result.discount_direct += discount_direct // 直接折扣
            result.discount_amount += discount_direct
            result._activites.push(activite)
          }
        }
      })
    }

    // if (Array.isArray(list) && list.length > 0) {
    //   list = list.map(item => {
    //     item._activites = activites.filter(e => e._goods_nos.includes(item.goods_no))
    //     let onlyActivite = item._activites.find(e => (e.promotion_mode === '满额减现' && e
    //       .whether_multiplication === '是') || e.promotion_mode === '直接折扣')
    //     if (onlyActivite) {
    //       // 都是不倍增且满额减现的才可以叠加 有倍增的就只用倍增的 有直接折扣的就只用直接折扣的 
    //       item._activites = [onlyActivite]
    //     }
    //     return item
    //   })
    // }
  }

  if (Array.isArray(list) && list.length > 0) {
    list = JSON.parse(JSON.stringify(list))

    list.forEach(item => {
      const amount = item.amount || 0
      result.order_total_amount += amount * item.sale_price

      const obj = {
        goods_name: item.goods_name,
        "goods_no": item.goods_no,
        "goods_type": item.goods_type,
        "goods_barcode": item.goods_barcode,
        "goods_num": item.amount || 0,
        "amount": item.amount || 0,
        "sale_price": item.sale_price,
        "subtotal_amount": 0, //小计金额
        "discount_amount": 0, //优惠金额
        "ctual_amount": 0, //实收金额

        goods_stock: item.goods_stock,
        _vip_sub_amount: 0,
        _activite_info: item._activite_info,
        _sale_price: item.sale_price,
        _buy_full_discount: 0, //满额减现
        _buy_discount: 0, // 直接折扣
        _buy_discount_total: 0, //
        _buy_full_discount: 0,
        _buy_full_discount_total: 0,
        _integral_deduction: 0, //积分抵扣金额
        _activite: null,
        _activites: item._activites || [],
        _originPrice: Number(Number(item.sale_price * amount).toFixed(2)) // 原价小计
      }

      obj.subtotal_amount = amount * item.sale_price
      obj.ctual_amount = amount * item.sale_price

      let objActivites = null;
      if (obj.goods_num) {
        // if (type !== 'vip' && obj.goods_num) {
        objActivites = item._activites
        debugger
        if (Array.isArray(objActivites) && objActivites.length > 0) {
          objActivites.forEach(objActivite => {
            if (Array.isArray(objActivite._discountGoodsList) && objActivite._discountGoodsList.length > 0) {
              let _discountGoodsList = list.filter(e => objActivite._discountGoodsList.includes(e.goods_no))
              if (Array.isArray(_discountGoodsList) && _discountGoodsList.length > 0) {
                let totalPrice = 0
                _discountGoodsList.forEach(e => {
                  totalPrice += e.sale_price * e.amount
                })
                let curPrice = item.sale_price * item.amount
                let rate = curPrice / totalPrice
                if (objActivite.promotion_mode === '直接折扣') {
                  let discount = (objActivite.direct_discount || objActivite.discount || 100) / 100
                  obj._buy_discount = -toFixed2(item.sale_price - item.sale_price * discount)
                  obj._buy_discount_total = -toFixed2(item.amount * (item.sale_price - item.sale_price *
                    discount))
                  obj.discount_amount = obj._buy_discount_total
                  obj.ctual_amount += obj._buy_discount_total
                } else {
                  obj._buy_full_discount = -toFixed2(rate * objActivite.discount_amount / item
                    .amount) //满额减现 
                  obj._buy_full_discount_total = -toFixed2(rate * objActivite.discount_amount)
                  obj.discount_amount = obj._buy_full_discount_total
                  obj.ctual_amount += obj._buy_full_discount_total
                }
              }
            }
          })
        }
      }

      let price = item.sale_price * amount
      if (enable_member_discount === '是' && !couponInfo && (!type || type === 'vip') && !obj
        ._buy_discount_total && !obj
        ._buy_full_discount_total) { //使用会员价
        // if (enable_member_discount === '是' && type === 'vip') { //会员价
        const member_level_no = curMember?.member_level_no
        if (member_level_no && item.allow_member_price == '允许') {
          if (item?._goods_member && item?._goods_member[member_level_no] && item?._goods_member[
              member_level_no]
            .member_price_type !== '禁止' && item?._goods_member[
              member_level_no]?.member_discount_amount) { // 优先使用会员价 
            price = item?._goods_member[member_level_no]?.member_discount_amount * amount
          } else if (item?._goods_member && item?._goods_member[member_level_no] && item
            ?._goods_member[
              member_level_no].member_price_type !== '禁止' && item?._goods_member[
              member_level_no]
            ?.discount_rate) { // 其次会员折扣
            price = item?._goods_member[member_level_no]?.discount_rate * item.sale_price *
              amount / 100
          }

          obj._vip_sub_amount = price - item.sale_price * amount
          obj.discount_amount += obj._vip_sub_amount
          result.member_discount += obj._vip_sub_amount
          result.discount_amount += obj._vip_sub_amount

        }

        result.order_amount += price
      } else if (type === 'discount') {
        // 整单手动折扣 
        obj._finalPrice = Number(Number(obj.sale_price * Number(discountAmount) / 100).toFixed(
          2)) // 优惠价
        obj.subtotal_amount = obj._finalPrice * amount // 小计金额
        obj.ctual_amount = obj.subtotal_amount //实收金额
        // obj.discount_amount = obj.subtotal_amount - obj._originPrice
        obj._discount_sub_amount = obj.subtotal_amount - obj._originPrice
      } else if (type === 'change') {
        // 整单手动减免
        // obj._finalPrice = Number(Number(obj.sale_price - discountAmount).toFixed(2)) // 优惠价
        // obj.subtotal_amount = obj._finalPrice * amount // 小计金额
        // obj.ctual_amount = obj.subtotal_amount //实收金额
        // obj.discount_amount = obj.subtotal_amount - obj._originPrice
      } else if (type === 'free') {
        // 免单
        obj.subtotal_amount = 0
        obj.ctual_amount = 0
        obj.discount_amount = -obj._originPrice
      } else {
        result.order_amount += price
      }

      obj._id = item._id
      result.order_detail.push(obj)
    })


    if (result.discount_full_decrement) {
      result.order_amount += result.discount_full_decrement // 促销-满额减现
    }

    if (result.discount_direct) {
      result.order_amount += result.discount_direct //  促销-直接折扣
    }


    if (enable_member_discount == '是' && type === 'vip') {
      // result.member_discount = result.order_amount - result.order_total_amount
      // result.discount_amount = result.member_discount
    } else if (type === 'discount') {
      result.discount_mode = '折扣'
      result.discount_type = '整单手动打折/改价'
      result.order_amount = result.order_detail.reduce((pre, cur) => {
        pre += cur.subtotal_amount
        return pre
      }, 0)
      result.discount_reduction_amount = result.order_amount - result.order_total_amount
      result.discount_amount += result.discount_reduction_amount
      // result.change_price = result.order_amount      
      result.change_price = result.discount_reduction_amount
    } else if (type === 'change' && discountAmount) {
      // 整单手动减免
      result.order_amount = result.order_total_amount - discountAmount
      result.discount_reduction_amount = -discountAmount
      // result.discount_amount = -discountAmount
      result.discount_amount += result.discount_reduction_amount
      result.change_price = result.discount_reduction_amount

      // const rate = result.order_amount / result.order_total_amount
      result.order_detail = result.order_detail.map((cur, index) => {
        cur._change_sub_amount = -Number((discountAmount * cur._originPrice / result
          .order_total_amount).toFixed(
          2))
        // cur.subtotal_amount = Number(Number(cur.sale_price * cur.amount * rate).toFixed(2))
        // cur.discount_amount = cur.subtotal_amount - cur._originPrice
        // cur.ctual_amount = cur.subtotal_amount //实收金额
        return cur
      })

      result.discount_mode = '减免'
      result.discount_type = '整单手动打折/改价'

    } else if (type === 'free') {
      result.discount_type = '免单'
      result.order_amount = 0
      result._order_amount = 0
      result.discount_amount = -result.order_total_amount
      result.free_discount_amount = -result.order_total_amount
    }
    result._order_amount = result.order_amount

    /**
     * 积分抵扣
     */
    if (result.member_no && $integralSetting?.enable_member_integral === '是') {
      // 启用会员积分
      if ($integralSetting.integral_deduction === '启用') {
        // 启用积分抵扣
        // 每satisfy_deduction_integral,抵扣deduction_amount元
        if (!isNaN(Number(integralPayAmount))) {
          result.integral_deduction = toFixed2(-integralPayAmount)
          result.use_integral = toFixed2(integralPayAmount * $integralSetting.satisfy_deduction_integral)
          result.order_amount += result.integral_deduction
          result.discount_amount += result.integral_deduction
          result._order_amount = result.order_amount

          result.order_detail = result.order_detail.map(item => {
            item._integral_deduction = toFixed2(item.sale_price * item.amount * result.integral_deduction / result
              .order_total_amount)
            return item
          })
        }
      }
    }

    // 优惠券
    if (!['discount', 'change'].includes(type) && couponInfo && couponInfo.member_coupon_no) {
      if (type !== 'vip' && result.discount_direct === 0 && result.discount_full_decrement === 0) {
        const curTime = new Date().getTime()
        const startTime = new Date(couponInfo.available_start_time).getTime()
        const endTime = new Date(couponInfo.available_end_time).getTime()
        if (curTime < endTime && curTime > startTime) {
          // 在活动起止时间内
          if (couponInfo.use_threshold === '无门槛') {
            result.coupon_discount = couponInfo.discount_amount > result.order_amount ? -result.order_amount : -
              couponInfo.discount_amount
            result.discount_amount += result.coupon_discount
            result.coupon_no = couponInfo.member_coupon_no
          } else if (couponInfo.use_threshold === "最低消费") {
            if (result.order_total_amount >= couponInfo.min_consumption) {
              result.coupon_discount = couponInfo.discount_amount > result.order_amount ? -result.order_amount : -
                couponInfo.discount_amount
              result.discount_amount += result.coupon_discount
              result.coupon_no = couponInfo.member_coupon_no
            }
          }
          result.order_amount += result.coupon_discount
          result._order_amount = result.order_amount
        } else {
          uni.showToast({
            title: '不在可用时间范围内',
            icon: 'none'
          })
        }
      }
    }

    // 抹零相关计算
    if (type !== 'free' && subtractPrice) {
      result.cash_reduction_amount = -subtractPrice
      result.discount_amount = result._order_amount - result.order_total_amount - subtractPrice
      result._order_amount = result._order_amount - subtractPrice
    }
    if (!isNaN(vipPayAmount) && vipPayAmount > 0) {
      result._vip_pay_order_amount = result._order_amount - vipPayAmount
      result._vip_pay_amount = vipPayAmount
    }
  }

  let _coupon_discount = 0
  let other_discount_amount = 0
  const listLength = result.order_detail.length
  result.order_detail = result.order_detail.map((cur, index) => {
    // 将优惠金额按价格占比平均到每个商品
    cur.subtotal_amount = Number(Number(cur.sale_price * cur.amount).toFixed(2))
    cur._ml_sub_amount = -(subtractPrice * cur._originPrice / result.order_total_amount)
    cur._free_sub_amount = result.free_discount_amount ? (result.free_discount_amount * cur
      ._originPrice / result
      .order_total_amount) : 0

    if (result.coupon_discount) {
      if (index > 0 && index === listLength - 1) {
        cur._coupon_discount = toFixed2(result.coupon_discount - _coupon_discount)
      } else {
        cur._coupon_discount = toFixed2(result.coupon_discount * cur._originPrice / result.order_total_amount)
        _coupon_discount += cur._coupon_discount
      }
    }

    cur.discount_amount = toFixed2(cur._buy_discount_total) + toFixed2(cur._buy_full_discount_total) + toFixed2(
      cur._discount_sub_amount) + toFixed2(cur._change_sub_amount) + toFixed2(cur
      ._vip_sub_amount) + toFixed2(cur._ml_sub_amount) + toFixed2(cur._free_sub_amount) + toFixed2(cur
      ._integral_deduction) + toFixed2(cur._coupon_discount)

    cur.discount_amount = toFixed2(cur.discount_amount) //优惠价格
    cur.ctual_amount = toFixed2(cur.subtotal_amount + cur.discount_amount) //实收金额

    if (index !== listLength - 1) {
      other_discount_amount += toFixed2(cur.discount_amount)
    } else {
      cur.discount_amount = toFixed2(result.discount_amount - other_discount_amount)
    }

    return cur
  })

  // let other_discount_amount = 0
  // result.order_detail = result.order_detail.map((item, index) => {
  //   if (index !== result.order_detail.length - 1) {
  //     other_discount_amount += toFixed2(item.discount_amount)
  //   } else {
  //     item.discount_amount = toFixed2(result.discount_amount - other_discount_amount)
  //   }
  //   return item
  // })

  result.order_amount = result.order_total_amount + result.discount_amount
  result._order_amount = result.order_amount
  Object.keys(result).forEach(key => {
    if (result[key] && typeof result[key] === 'number') {
      result[key] = Number(Number(result[key]).toFixed(2))
    }
  })

  return result
}


/**
 * @description 计算此商品的结算价
 * @param { object } e - 商品信息
 */
export const calcFinalPrice = (e = {}) => {
  // 目前只需要单价*数量
  let price = e.sale_price
  let amount = e?.amount || e?.goods_num

  if (price && amount) {
    const _finalPrice = Number(toFixed2(price * amount))
    return {
      ...e,
      _finalPrice
    }
  }
  return JSON.parse(JSON.stringify(e))
}

/**
 * @description 给数字前面添加人民币符号
 */
export const setMoneyStr = (num) => {
  num = Number(num)
  let str = `￥${Math.abs(num)}`
  if (num < 0) {
    str = `-${str}`
  }
  return str
}
